﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EvinceUI.JQueryDataTable.Model;
using EvincePayroll.Data;
using EvincePayroll.Utility;
using EvinceUI;
using System.Text;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using EvinceUI.Models;
namespace EvinceUI.Controllers
{
    public class LeaveRequestsController : Controller
    {
        //
        // GET: /LeaveRequests/
        [Authorize.SessionExpire]
        public ActionResult LeaveRequestsAdmin()
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            EvincePayrollService homeService = new EvincePayrollService(ServiceTypes.Home);
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            
            ViewBag.Name = employeeService.GetEmployeeList(employee.Email);//emp
            ViewBag.Status = homeService.getStatus(employee.Email);//home
            ViewBag.AssignTo = leaveRequestService.GetLeaveRequestsEmployeeData(employee.Email, Constants.USER_ROLE_JUNIORDEVELOPER);//leave
            ViewBag.ReportTo = leaveRequestService.GetLeaveRequestsEmployeeData(employee.Email, Constants.USER_ROLE_JUNIORDEVELOPER);//
            
            return View();
        }

        [Authorize.SessionExpire]
        public ActionResult AjaxGetLeaveRequestsAdmin(JQueryDataTableParamModel param)
        {
            List<EmployeeLeaveRequestData> leaveRequestList;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            leaveRequestList = leaveRequestService.LeaveRequestsAdmin(employee.Email);
            if (leaveRequestList != null)
            {
                IEnumerable<EmployeeLeaveRequestData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered

                    var employeeIdFilter = Convert.ToString(Request["sSearch_0"]);
                    var employeeNameFilter = Convert.ToString(Request["sSearch_1"]);
                    var reportManagerFilter = Convert.ToString(Request["sSearch_2"]);




                    //Optionally check whether the columns are searchable at all

                    var isEmployeeIdSearchable = Convert.ToBoolean(Request["bSearchable_0"]);
                    var isEmployeeNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                    var isReportManagerSearchable = Convert.ToBoolean(Request["bSearchable_2"]);




                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "EmployeeId.ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "EmployeeName.ToString().ToUpper()")).Append(")||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "ReportManager.ToString().ToUpper()")).Append(")");
                        filteredRequests = leaveRequestList;
                    }
                    else
                    {

                        filteredRequests = leaveRequestList
                        .Where(d => isEmployeeIdSearchable && d.EmployeeStringId.ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isEmployeeNameSearchable && d.EmployeeFullName.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isReportManagerSearchable && d.ReportingManagerName.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        );

                    }
                }
                else
                {
                    filteredRequests = leaveRequestList;

                }

                var isEmployeeId = Convert.ToBoolean(Request["bSortable_0"]);
                var isEmployeeName = Convert.ToBoolean(Request["bSortable_1"]);
                var isReportManager = Convert.ToBoolean(Request["bSortable_2"]);



                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<EmployeeLeaveRequestData, string> orderingFunction = (d => sortColumnIndex == 1 && isEmployeeId ? d.EmployeeStringId.ToString() :
                sortColumnIndex == 2 && isEmployeeName ? d.EmployeeFullName.ToString() :
                sortColumnIndex == 3 && isReportManager ? d.ReportingManagerName.ToString() :
                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                             p.LeaveId.ToString(), 
                             p.EmployeeStringId, 
                             p.EmployeeFullName, 
                             p.LeaveReason,
                             p.LeaveStatus,
                             p.LeaveType,
                             p.FromDate.ToShortDateString(), 
                             p.ToDate.ToShortDateString(),
                             p.ReportingManagerName,
                             GetLinks(p.LeaveStatus,p.LeaveId,p.FromDate,p.ToDate),
                             CreateLeaveWithdrawLink(p.LeaveId.ToString(),p.LeaveStatus,true)
                             //string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this,{2},'{3}','{4}')\" id=\"{0}\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{1}\" /></a>",Convert.ToString(p.LeaveId),Convert.ToString(p.LeaveId),GetDays(p.FromDate,p.ToDate),Convert.ToString(p.FromDate),p.LeaveId)+" / "+
                             //string.Format("<a href=\"#\" onclick=\"updateStatusReject(this,'{2}')\" id=\"{0}\" class=\"RejectStatus\">Reject<input type=\"hidden\" value=\"{1}\" /></a>",Convert.ToString(p.LeaveId),Convert.ToString(p.LeaveId),p.LeaveId)
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = leaveRequestList.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
        }

        public string GetLinks(string status,Guid leaveId,DateTime fromDate,DateTime toDate)
        {
            string statusValue = string.Empty;
            if (status == Constants.LEAVE_REQUEST_PENDING)
            {

                statusValue = string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this,{2},'{3}','{4}')\" id=\"{0}\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{1}\" /></a>", Convert.ToString(leaveId), Convert.ToString(leaveId), GetDays(fromDate, toDate), Convert.ToString(fromDate), leaveId) + " / " +
                                  string.Format("<a href=\"#\" onclick=\"updateStatusReject(this,'{2}','{3}','{4}',1)\" id=\"{0}\" class=\"RejectStatus\">Reject<input type=\"hidden\" value=\"{1}\" /></a>", Convert.ToString(leaveId), Convert.ToString(leaveId), GetDays(fromDate, toDate), Convert.ToString(fromDate), leaveId);
            }
            else if(status==Constants.LEAVE_REQUEST_APPROVED) {
                              //string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this,{2},'{3}','{4}')\" id=\"{0}\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{1}\" /></a>", Convert.ToString(leaveId), Convert.ToString(leaveId), GetDays(fromDate, toDate), Convert.ToString(fromDate), leaveId)
                statusValue = string.Format("<a href=\"#\" onclick=\"updateStatusReject(this,'{2}','{3}','{4}',1)\" id=\"{0}\" class=\"RejectStatus\">Reject<input type=\"hidden\" value=\"{1}\" /></a>", Convert.ToString(leaveId), Convert.ToString(leaveId), GetDays(fromDate, toDate), Convert.ToString(fromDate), leaveId);
            
            }
            else if (status == Constants.LEAVE_REQUEST_NOT_APPROVED)
            {
                statusValue = string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this,{2},'{3}','{4}')\" id=\"{0}\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{1}\" /></a>", Convert.ToString(leaveId), Convert.ToString(leaveId), GetDays(fromDate, toDate), Convert.ToString(fromDate), leaveId);//+"/"+
                    //string.Format("<a href=\"#\" onclick=\"updateStatusUnApprove(this,{2},'{3}','{4}')\" id=\"{0}\" class=\"ApproveStatus\">UnApprove<input type=\"hidden\" value=\"{1}\" /></a>", Convert.ToString(leaveId), Convert.ToString(leaveId), GetDays(fromDate, toDate), Convert.ToString(fromDate), leaveId);

            }
            //else if (status == Constants.LEAVE_REQUEST_UN_APPROVED)
            //{
            //    statusValue = string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this,{2},'{3}','{4}')\" id=\"{0}\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{1}\" /></a>", Convert.ToString(leaveId), Convert.ToString(leaveId), GetDays(fromDate, toDate), Convert.ToString(fromDate), leaveId);
                    

            //}
            return statusValue;
        
        }

        public double GetDays(DateTime from,DateTime to)
        {
            int total = 0;
            if (to != null)
            {
                total = Math.Abs(to.Subtract(from).Days);
                //TimeSpan day = fromDate - toDate;
                
            }
            
            return total+1;
        }



        [Authorize.SessionExpire]
        public ActionResult EmployeeLeaveRequestAndStatus()
        {

            return View();
        }

        public PartialViewResult _GetLeaveRequestTable()
        {
            return PartialView();
        }
        [Authorize.SessionExpire]
        public ActionResult AjaxGetLeaveRequestsEmployee(JQueryDataTableParamModel param, string status)
        {
            if (status == null)
                status = Constants.NA;
            List<EmployeeLeaveRequestData> leaveRequestList;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            leaveRequestList = leaveRequestService.GetRequestEmployee(employee.Email, status);
            if (leaveRequestList != null)
            {
                IEnumerable<EmployeeLeaveRequestData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered


                    var createdDateFilter = Convert.ToString(Request["sSearch_1"]);
                    var TypeFilter = Convert.ToString(Request["sSearch_3"]);
                    var FromFilter = Convert.ToString(Request["sSearch_4"]);
                    var ToFilter = Convert.ToString(Request["sSearch_5"]);

                    var StatusFilter = Convert.ToString(Request["sSearch_6"]);






                    //Optionally check whether the columns are searchable at all

                    var isCreatedDateSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                    var isType = Convert.ToBoolean(Request["bSearchable_3"]);
                    var isFrom = Convert.ToBoolean(Request["bSearchable_4"]);
                    var isTo = Convert.ToBoolean(Request["bSearchable_5"]);
                    var isStatus = Convert.ToBoolean(Request["bSearchable_6"]);




                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "CreatedDate.ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Type.ToString().ToUpper()")).Append(")||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "From.ToString().ToUpper()")).Append(")");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "To.ToString().ToUpper()")).Append(")");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Status.ToString().ToUpper()")).Append(")");

                        filteredRequests = leaveRequestList;
                    }
                    else
                    {

                        filteredRequests = leaveRequestList
                        .Where(d => isCreatedDateSearchable && d.CreatedDate.ToString().Contains(param.sSearch.Trim().ToLower())
                         ||
                        isType && d.LeaveType.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isFrom && d.FromDate.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isTo && d.ToDate.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isFrom && d.LeaveStatus.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())

                        );

                    }
                }
                else
                {
                    filteredRequests = leaveRequestList;

                }

                var isCreatedDate = Convert.ToBoolean(Request["bSortable_1"]);
                var isType1 = Convert.ToBoolean(Request["bSortable_3"]);
                var isFrom1 = Convert.ToBoolean(Request["bSortable_4"]);
                var isTo1 = Convert.ToBoolean(Request["bSortable_5"]);
                var isStatus1 = Convert.ToBoolean(Request["bSortable_6"]);




                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<EmployeeLeaveRequestData, string> orderingFunction = (//d => sortColumnIndex == 1 && isEmployeeId ? d.EmployeeStringId.ToString() :
               d => sortColumnIndex == 1 && isCreatedDate ? d.CreatedDate.ToString() :
                sortColumnIndex == 3 && isType1 ? d.LeaveType.ToString() :
                sortColumnIndex == 4 && isFrom1 ? d.FromDate.ToString() :
                sortColumnIndex == 4 && isTo1 ? d.ToDate.ToString() :
                sortColumnIndex == 6 && isStatus1 ? d.LeaveStatus.ToString() :
                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                             p.LeaveId.ToString(), 
                             p.CreatedDate.ToShortDateString(),
                             p.LeaveReason, 
                             p.LeaveType,
                             p.FromDate.ToShortDateString(), 
                             p.ToDate.ToShortDateString(),
                             p.LeaveStatus,
                             p.Remark,
                             CreateLeaveWithdrawLink(p.LeaveId.ToString(),p.LeaveStatus,false)

                             
                            // string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this)\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{0}\" /></a>",Convert.ToString(p.LeaveId))+"/"+
                             //string.Format("<a href=\"#\" onclick=\"updateStatusReject(this)\" class=\"RejectStatus\">Reject<input type=\"hidden\" value=\"{0}\" /></a>",Convert.ToString(p.LeaveId))
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = leaveRequestList.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
        }

        public string CreateLeaveWithdrawLink(string leaveRequestId,string status,bool flag)
        {
            string result = string.Empty;
            if (flag == false)
            {
                if (!string.IsNullOrEmpty(leaveRequestId) && status.Equals(Constants.LEAVE_REQUEST_PENDING))// || status.Equals(Constants.LEAVE_REQUEST_APPROVED))
                    result = string.Format("<a href=\"#\" onclick=\"WithdrawLeave('{0}',false)\" id=\"{1}\">Withdraw</a>", leaveRequestId, leaveRequestId);
            }
            else if (flag == true)
            {
                if (!string.IsNullOrEmpty(leaveRequestId) && status.Equals(Constants.LEAVE_REQUEST_PENDING) || status.Equals(Constants.LEAVE_REQUEST_APPROVED))
                    result = string.Format("<a href=\"#\" onclick=\"WithdrawLeave('{0}',true)\" id=\"{1}\">Withdraw</a>", leaveRequestId, leaveRequestId);
            
            }
            return result;
        }

        [Authorize.SessionExpire]
        public ActionResult LeaveWithdraw(string leaveRequestId,bool flag)
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            bool result = leaveRequestService.LeaveWithdraw(employee.Email, leaveRequestId,flag);
            return Json(new {result }, JsonRequestBehavior.AllowGet);
        }


        [Authorize.SessionExpire]
        public PartialViewResult _LeaveRequestsEmployee()
        {
            
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            EvincePayrollService homeService = new EvincePayrollService(ServiceTypes.Home);
            ViewBag.AssignTo = leaveRequestService.GetLeaveRequestsEmployeeData(employee.Email,Constants.USER_ROLE_JUNIORDEVELOPER);
            ViewBag.ReportTo = leaveRequestService.GetLeaveRequestsEmployeeData(employee.Email, Constants.USER_ROLE_SENIOR_DEVELOPER);
            var LeaveType = homeService.GetAppOption(employee.Email, Constants.LeaveType);
            ViewBag.LeaveType = LeaveType;
            ViewBag.Sick = LeaveType.Where(x => x.ParamValue.Equals(Constants.LeaveType_SICK)).Select(x => x.ParamId).FirstOrDefault();
            ViewBag.PL = LeaveType.Where(x => x.ParamValue.Equals(Constants.LeaveType_PL)).Select(x => x.ParamId).FirstOrDefault();
            ViewBag.CL = LeaveType.Where(x => x.ParamValue.Equals(Constants.LeaveType_CL)).Select(x => x.ParamId).FirstOrDefault();
            ViewBag.LWP = LeaveType.Where(x => x.ParamValue.Equals(Constants.LeaveType_LWP)).Select(x => x.ParamId).FirstOrDefault();
            return PartialView();
        }

        [Authorize.SessionExpire]
        public PartialViewResult _CurrentLeavesInAccount()
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            var leaveData = leaveRequestService.GetEmoloyeeLeaveMasterData(employee);
            return PartialView(leaveData);
        }

        [Authorize.SessionExpire]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LeaveRequestsEmployee(EmployeeLeaveRequestData employeeLeaveData, string emailId, string leaveType, string FromDate, string ToDate)
        {
            List<EmployeeLeaveRequestData> leaveRequestList;
            var i = employeeLeaveData.LeaveTypes;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            employeeLeaveData.EmployeeId = employee.ID;
            employeeLeaveData.FromDate =DateTime.ParseExact(FromDate,"MM/dd/yyyy",null);
            if (string.IsNullOrEmpty(ToDate))
                employeeLeaveData.ToDate = employeeLeaveData.FromDate;
            else
                employeeLeaveData.ToDate = DateTime.ParseExact(ToDate, "MM/dd/yyyy", null);
            employeeLeaveData.TotalLeave = GetDays(employeeLeaveData.FromDate,employeeLeaveData.ToDate).ToString();

            


            leaveRequestList = leaveRequestService.LeaveRequestsEmployee(employeeLeaveData,employee.Email);
           

            return RedirectToAction("EmployeeLeaveRequestAndStatus");



        }
        public TimeSpan GetTime(string start, string end)
        {
            string totalTime = string.Empty;
            DateTime startTime = DateTime.Parse(start);
            DateTime endTime = DateTime.Parse(end);
            TimeSpan ts = endTime - startTime;

            return ts;
        }


        private string GetExpression(string p)
        {
            throw new NotImplementedException();
        }
        [Authorize.SessionExpire]
        public ActionResult UpdateLeaveRequestStatus(string leaveRequestId, string status, string message, string numberOfDays, DateTime fromDate,string flag)
        {
            if(leaveRequestId==null)
                leaveRequestId=Constants.NA;
            if(status==null)
                status=Constants.NA;
            if(message==null)
                message=Constants.NA;
            if(numberOfDays==null)
                numberOfDays=Constants.NA;
            if (flag == null)
                flag = Constants.NA;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            bool result = leaveRequestService.UpdateLeaveRequestStatus(employee.Email, leaveRequestId,  status, message,numberOfDays,fromDate,flag);
            if (result == true)
            {
                
                
            }
            return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);
        }
        public void MailSend(string emailId)
        {
            //....Here is the code for sending a mail.....

            var fromAddress = "sandeep.evince@gmail.com";// Gmail Address from where you send the mail
            var toAddress = emailId;
            const string fromPassword = "evinceadmin";//Password of your gmail address
            string subject = "testing mail";
            string body = "From: Admin \n";
            body += "Email: \n";
            body += "Subject: \n";
            body += "Question: ";
            var smtp = new System.Net.Mail.SmtpClient();
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;
            }
            smtp.Send(fromAddress, toAddress, subject, body);
            
        }

        [Authorize.SessionExpire]
        public ActionResult LeaveMaster()
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);
            ViewBag.UserRoleList = userRoleService.GetUserRoleList(employee.Email);
            return View();
        }

        [Authorize.SessionExpire]
        public ActionResult CreateLeaveMaster(LeaveMasterData leaveMaster, string leaveMasterId="")
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            leaveMaster.Year = DateTime.Today;
            if (!string.IsNullOrEmpty(leaveMasterId))
            {
                leaveMaster.LeaveMasterId = new Guid(leaveMasterId);
            }
            leaveRequestService.CreateLeaveMaster(leaveMaster,employee.Email);

            return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);
        }

        [Authorize.SessionExpire]
        public PartialViewResult _CurrentLeaveData(string roleId)
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            var leaveData = leaveRequestService.GetLeaveMasterData(employee.Email,roleId);
            var list = new List<TotalLeaves>();
            for (int i = 1; i <= 40; i++)
            {
                list.Add(new TotalLeaves() { Text = i.ToString(), Value = i.ToString() });
            }
            ViewBag.List = list;
            return PartialView(leaveData);
        }

        public ActionResult CheckLeave(string leaveType)
        {
            bool result = false;
            if (leaveType != "")
            {
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
                result = leaveRequestService.CheckLeave(leaveType,employee.Email);
            
            
            }


            return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);
        }

        #region "CRUD OPERATION"
        //public int AddData(EmployeeLeaveRequestData employeeLeaveRequest , Guid Id , string emailId)
        public ActionResult AddData(EmployeeLeaveRequestData employeeLeaveRequest, string leaveType,string FromDate,string ToDate)
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
            employeeLeaveRequest.FromDate = DateTime.ParseExact(FromDate, "MM/dd/yyyy", null);
            if (string.IsNullOrEmpty(ToDate))
                employeeLeaveRequest.ToDate = employeeLeaveRequest.FromDate;
            else
                employeeLeaveRequest.ToDate = DateTime.ParseExact(ToDate, "MM/dd/yyyy", null);
            employeeLeaveRequest.TotalLeave = GetDays(employeeLeaveRequest.FromDate, employeeLeaveRequest.ToDate).ToString();
            employeeLeaveRequest.LeaveType = leaveType;
            bool result = leaveRequestService.AddData(employeeLeaveRequest,employee.Email);
            return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);
            //return true;
        }

        //public string UpdateData(Guid id, string value, int? rowId, int? columnPosition, int? columnId, string columnName)
        //{
        //    //EvincePayrollService ws = new EvincePayrollService(ServiceTypes.Employee);
            
        //    //string result = ws.UpdateData(employeeLeaveRequest, Id, emailId);
        //    //return result;
        //    EmployeeData employee = (EmployeeData)Session["EmployeeData"];
        //    EmployeeLeaveRequestData employeeLeaveRequest = null;
        //    EvincePayrollService ws = new EvincePayrollService(ServiceTypes.Employee);
        //    var leaveRequestList = ws.LeaveRequestsAdmin(employee.Email);

        //    if (columnPosition == 0 && leaveRequestList.Any(c => c.EmployeeStringId.ToLower().Equals(value.ToLower())))
        //        return "Company with a name '" + value + "' already exists";
        //    var leaveRequest = leaveRequestList.FirstOrDefault(c => c.LeaveId == id);
        //    if (leaveRequest == null)
        //    {
        //        return "Leave with an id = " + id + " does not exists";
        //    }
        //    switch (columnPosition)
        //    {
        //        //case 0:
        //        //    leaveRequestId.EmployeeStringId = value;
        //        //    break;
        //        //case 1:
        //        //    leaveRequestId.ReportingManagerName = value;
        //        //    break;
        //        case 2:
        //            employeeLeaveRequest = new EmployeeLeaveRequestData();
        //           employeeLeaveRequest.LeaveId = id;
                   
        //            employeeLeaveRequest.LeaveReason=value;
        //            employeeLeaveRequest.EmployeeId = leaveRequest.EmployeeId;
        //            employeeLeaveRequest.TotalLeave = leaveRequest.TotalLeave;
        //            employeeLeaveRequest.LeaveStatus = leaveRequest.LeaveStatus;
        //            employeeLeaveRequest.LeaveType = leaveRequest.LeaveType;
        //            employeeLeaveRequest.FromDate = leaveRequest.FromDate;
        //            employeeLeaveRequest.ToDate = leaveRequest.ToDate;
        //            employeeLeaveRequest.Status = leaveRequest.Status;
        //            employeeLeaveRequest.ReportingManagerName = leaveRequest.ReportingManagerName;
        //            employeeLeaveRequest.ReportTo = leaveRequest.ReportTo;
        //            employeeLeaveRequest.AssignTo = leaveRequest.AssignTo;
        //            employeeLeaveRequest.Remark = leaveRequest.Remark;
                    

        //            bool result = ws.UpdateData(employeeLeaveRequest, id, employee.Email);
                    
                    
        //            break;
        //        case 3:
        //            employeeLeaveRequest = new EmployeeLeaveRequestData();
        //            employeeLeaveRequest.LeaveId = id;
        //            employeeLeaveRequest.EmployeeId = leaveRequest.EmployeeId;
        //            employeeLeaveRequest.LeaveReason=leaveRequest.LeaveReason;;
        //            employeeLeaveRequest.TotalLeave = leaveRequest.TotalLeave;
        //            employeeLeaveRequest.LeaveStatus = leaveRequest.LeaveStatus;
        //            employeeLeaveRequest.LeaveType = value;
        //            employeeLeaveRequest.FromDate = leaveRequest.FromDate;
        //            employeeLeaveRequest.ToDate = leaveRequest.ToDate;
        //            employeeLeaveRequest.Status = leaveRequest.Status;
        //            employeeLeaveRequest.ReportTo = leaveRequest.ReportTo;
        //            employeeLeaveRequest.AssignTo = leaveRequest.AssignTo;
        //            employeeLeaveRequest.Remark = leaveRequest.Remark;
                    

        //            bool result1 = ws.UpdateData(employeeLeaveRequest, id, employee.Email);
                    
                   
        //            break;
        //        case 4:
        //            employeeLeaveRequest = new EmployeeLeaveRequestData();
        //            employeeLeaveRequest.LeaveId = id;
        //            employeeLeaveRequest.EmployeeId = leaveRequest.EmployeeId;
        //            employeeLeaveRequest.LeaveReason=leaveRequest.LeaveReason;
        //            employeeLeaveRequest.TotalLeave = leaveRequest.TotalLeave;
        //            employeeLeaveRequest.LeaveStatus = leaveRequest.LeaveStatus;
        //            employeeLeaveRequest.LeaveType = employeeLeaveRequest.LeaveType;
        //            employeeLeaveRequest.FromDate = value;
        //            employeeLeaveRequest.ToDate = leaveRequest.ToDate;
        //            employeeLeaveRequest.Status = leaveRequest.Status;
        //            employeeLeaveRequest.ReportTo = leaveRequest.ReportTo;
        //            employeeLeaveRequest.AssignTo = leaveRequest.AssignTo;
        //            employeeLeaveRequest.Remark = leaveRequest.Remark;
                    

        //            bool result2 = ws.UpdateData(employeeLeaveRequest, id, employee.Email);
                    
        //            break;
        //        case 5:
        //            employeeLeaveRequest.LeaveId = id;
        //            employeeLeaveRequest.EmployeeId = leaveRequest.EmployeeId;
        //            employeeLeaveRequest.LeaveReason=leaveRequest.LeaveReason;
        //            employeeLeaveRequest.TotalLeave = leaveRequest.TotalLeave;
        //            employeeLeaveRequest.LeaveStatus = leaveRequest.LeaveStatus;
        //            employeeLeaveRequest.LeaveType = leaveRequest.LeaveType;
        //            employeeLeaveRequest.FromDate = leaveRequest.FromDate;
        //            employeeLeaveRequest.ToDate = value;
        //            employeeLeaveRequest.Status = leaveRequest.Status;
        //            employeeLeaveRequest.ReportTo = leaveRequest.ReportTo;
        //            employeeLeaveRequest.AssignTo = leaveRequest.AssignTo;
        //            employeeLeaveRequest.Remark = leaveRequest.Remark;
                    

        //            bool result3 = ws.UpdateData(employeeLeaveRequest, id, employee.Email);
                    
        //            break;
        //        default:
        //            break;
        //    }
        //    return value;
        //}

        public string DeleteData(int id, string emailId)
        {
            try
            {
                EvincePayrollService leaveRequestService = new EvincePayrollService(ServiceTypes.LeaveRequest);
                string result = leaveRequestService.DeleteData(id, emailId);
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }



        #endregion
    }
}
